<?php 
namespace xfyzf\plugins\wxpaypc\controller;
use xfyzf\api\controller\Examine;

class Index{
     public $priKey;
    public $info = [
        'name'        => 'wxpaypc', //支付插件英文名称，需和目录名称一致，不能有重复
		'showname'    => '微信回调插件补偿版', //支付插件显示名称
		'author'      => 'afei66', //支付插件作者
        'auth'        =>false,//授权开关
		'pwd'         =>'',//明文 密码
		'path'        =>'',//授权效验文件  注意 必须唯一 结尾.ini
        ];
    public function pc_upqr(){//更新二维码状态
        $postdata = input("");
        $token    = $postdata['token'];
        $name     = $postdata['wx_name'];
        $wxid     = $postdata['wxid'];
        $status   = $postdata['status']??0;
        Examine::checkRequiredParams(array($token,$name,$wxid));
        $authtoken = Examine::usertokendecode($token);
        if(!$authtoken)exitjson(-1,"token错误");
        
        $pid = $authtoken['pid'];
        $QR_row = $this->QR_row($name,$pid);
        $timess = time() +  180;
        if(!$QR_row)exitjson(-1,'二维码不存在');
        $sql = "update `pay_qrlist` set `cookie`='wxpaypcplugins',`crontime`='{$timess}',`status` = {$status} ,`uin`='{$wxid}' WHERE `id`='{$QR_row['id']}'";
        if(executeSQLQuery($sql, 'update'))exitjson(200,'更新二维码成功');
        exitjson(-1,'更新二维码失败！');
    }
    public function pc_cron(){//计划任务 更新
        global  $conf;
        Examine::cronkey(input("get")['key']);
        $timess=time() + mt_rand(60, 120);
        $times = time() +  180;
        $sql = "SELECT * FROM pay_qrlist WHERE `type` ='wxpay' and `cookie`='wxpaypcplugins' AND `status` = '1' AND crontime<'{$timess}'  AND hook_type = '1'";
        $rs = safeSqlQuery($sql, []);
        
        if($rs['count']>0){
             $ids = [];
             foreach ($rs['result'] as $res) {
                $ids[] = $res['id'];
             }
             $ids_str = implode(',', $ids);
             $update_sql = "UPDATE `pay_qrlist` SET `crontime`='{$times}', `status`='1' WHERE `id` IN ({$ids_str})";
             executeSQLQuery($update_sql, 'update');
             
        }
        echo 'Cron ok';
    }
    public function pc_notify(){
        $postdata  = input("post");
        $token     = $postdata['token'];
        $name      = $postdata['wx_name'];
        $wxid      = $postdata['wxid'];
        $money     = $postdata['money'];
        Examine::checkRequiredParams(array($token,$name,$wxid,$money));
        $authtoken = Examine::usertokendecode($token);
        if(!$authtoken)exitjson(-1,"token错误");
        $pid = $authtoken['pid'];
        $QR_row = $this->QR_row($name,$pid,$wxid);
        if(!$QR_row)exitjson(-1,'二维码不存在');
        $sql = "SELECT * FROM pay_order WHERE status=:status  and type=:type and price=:money and outtime>:time and pid = :pid and qr_id = :qr_id  limit 1";
        $paramsSelect = [
            'pid' => $pid,
            'type'=> "wxpay",
            'money' => $money,
            'time'=>time(),
            'qr_id' => $QR_row['id'],
            'status'=>0
        ];
        $srow = safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
        if($srow){
            if($srow['status'] == '0'){
                $E_type = "微信PC挂机";
                $url=creat_callback($srow);
                $data=get_curl($url['notify']);
                xfhtemail($pid,$money,$E_type,$srow['name'],$srow['trade_no']); 
                createLog($pid,'自动回调订单('.$E_type.')：'.$srow['trade_no'],http_ip());
                $arr = array(
                    'trade_no'=>$srow['trade_no'],
                    'money'=>$money,
                    'qr_id'=>$res['id']
                );
                Examine::exitWithMessage(200,'success',$arr);
            }
        }else{
            exitjson(-1,'无匹配金额');
        }
    }
    
    private function QR_row($name,$pid ,$uid = null){
        $where = (empty($uid))?'':" and `uin` = '{$uid}'";

        $sql = "SELECT * FROM pay_qrlist WHERE `type`='wxpay' and `pid`=:pid and `hook_type` = '1' and `beizhu`=:beizhu {$where} LIMIT 1";
        $paramsSelect = [
         
            'beizhu'=>$name,
            'pid' => $pid
        ];
        
        return safeSqlQuery($sql, $paramsSelect)['result'][0]??'';
    }
    
}
?>